package mju.cxf.handler;

import com.fasterxml.jackson.core.JsonParseException;
import lombok.extern.slf4j.Slf4j;
import mju.cxf.constant.MessageConstant;
import mju.cxf.exception.BaseException;
import mju.cxf.result.Result;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 公共异常处理 全局
 */
@RestControllerAdvice
@Slf4j
@Order(1)
public class GlobalExceptionHandler {
    /**
     * 捕获请求数据异常
     * @param ex
     * @return
     */
    @ExceptionHandler(JsonParseException.class)
    public Result JsonParseHandler(JsonParseException ex){
        return Result.error(MessageConstant.MESSAGE_BAD_REQUEST);
    }

    /**
     * 捕获文件流异常
     * @param ex
     * @return
     */
    @ExceptionHandler(IOException.class)
    public Result<String> IoHandler(IOException ex){
        String message = ex.getMessage();
        System.out.println(message);
        return Result.error(ex.getMessage());
    }
    /**
     * 捕获重复添加异常
     * @param ex
     * @return
     */

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result<String>  SQLIntegrityConstraintViolationExceptionHandler(SQLIntegrityConstraintViolationException ex){
        return Result.error(MessageConstant.DATA_DUPLICATION);
    }
    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result<String> BaseExceptionHandler(BaseException ex){
        return Result.error(ex.getMessage());
    }
    @ExceptionHandler
    @Order(2)
    public Result<String> exceptionHandler(Exception ex){
        ex.printStackTrace();
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(ex.getMessage());
    }

}
